using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;

namespace Tyng
{
    /// <summary>
    /// A class that combines command line, environment variable and app setting lookups in to a single lookup.
    /// </summary>
    /// <remarks>
    /// Order of failover is from command line, to environment variable and finally to app settings.
    /// </remarks>
    public static class HybridSettings
    {
        //TODO: use a more generic provider model here or something and just default to command line / env var / app settings...
        private static Dictionary<string, string> _cl;

        private static Dictionary<string, string> CommandLine
        {
            get
            {
                if (_cl == null)
                {
                    ParseCommandLine();
                }

                return _cl;
            }
        }

        private static void ParseCommandLine()
        {
            _cl = new Dictionary<string, string>();

            string cl = Environment.CommandLine;

            if (!string.IsNullOrEmpty(cl))
            {
                string[] clVars = cl.Split(' ');

                for (int i = 0; i < clVars.Length; i++)
                {
                    if (!string.IsNullOrEmpty(clVars[i]))
                    {
                        string[] pair = clVars[i].Split('=');

                        if (pair.Length == 2)
                        {
                            _cl.Add(pair[0], pair[1]);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Get app setting value
        /// </summary>
        /// <param name="name">Setting key</param>
        /// <returns>Value for key</returns>
        public static string GetValue(string name)
        {
            if (CommandLine.ContainsKey(name))
                return CommandLine[name];

            string temp = Environment.GetEnvironmentVariable(name);

            if (temp == null)
                return ConfigurationManager.AppSettings[name];
            else
                return temp;
        }
    }
}
